﻿using IMClient.Cache.Repositories;
using IMClient.Model.DataBase;
using IMClient.Model.DTO;

namespace IMClient.Model
{
    public static class User
    {
        public static string UserId { get; set; } = null!;
        public static string? UserName { get; set; }
        public static string? UserAvatar { get; set; }
        public static List<FriendDto>? FriendList { get; set; }
        public static List<GroupDto>? GroupList { get; set; }

        // 重新加载好友事件
        public static event Action? OnFriendListUpdated;

        // 重新加载群组事件
        public static event Action? OnGroupListUpdated;

        public static async void UpdatedFromServer()
        {
            // 从数据库中读取好友
            List<FriendDataBase> friendDatabaseList =
                await FriendCacheRepository.Instance.GetCachedFriendsAsync(UserId!);

            List<FriendDto> friendList = new List<FriendDto>(friendDatabaseList.Select(f =>
                new FriendDto { UserId = f.FriendId, UserName = f.FriendName, Avatar = f.FriendAvatar }).ToArray());

            if (!AreSetsEqual(FriendList!, friendList))
            {
                List<FriendDataBase> newFriendList = new List<FriendDataBase>(FriendList!.Select(f =>
                    new FriendDataBase
                    {
                        UserId = UserId!, FriendId = f.UserId, FriendName = f.UserName, FriendAvatar = f.Avatar!,
                        LastUpdateTime = DateTime.Now
                    }));
                
                await FriendCacheRepository.Instance.CacheFriendsAsync(UserId, newFriendList);
                OnFriendListUpdated?.Invoke();
            }
            
            // 从数据库中读取群组
            
            List<GroupDataBase> groupDatabaseList = await GroupCacheRepository.Instance.GetCachedGroupsAsync(UserId!);
            List<GroupDto> groupList = new List<GroupDto>(groupDatabaseList.Select(g =>
                new GroupDto { GroupId = g.GroupId, GroupName = g.GroupName, Avatar = g.GroupAvatar }).ToArray());
            
            if (!AreSetsEqual(GroupList!, groupList))
            {
                List<GroupDataBase> newGroupList = new List<GroupDataBase>(GroupList!.Select(g =>
                    new GroupDataBase
                    {
                        UserId = UserId!,
                        GroupId = g.GroupId!,
                        GroupName = g.GroupName!,
                        GroupAvatar = g.Avatar!,
                        Creator = g.Creator!,
                        LastUpdateTime = DateTime.Now
                    }));
                
                await GroupCacheRepository.Instance.CacheGroupsAsync(UserId, newGroupList);
                OnGroupListUpdated?.Invoke();
            }
        }

        private static bool AreSetsEqual<T>(IEnumerable<T> first, IEnumerable<T> second)
        {
            var set1 = new HashSet<T>(first);
            var set2 = new HashSet<T>(second);

            return set1.SetEquals(set2);
        }
    }
}